import Vue from 'vue'
import Router from 'vue-router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import store from '../store'

Vue.use(Router)

// 异步加载路由组件
const Login = () => import('@/views/Login.vue')
const Layout = () => import('@/views/Layout.vue')
const NotFound = () => import('@/views/404.vue')
const Dashboard = () => import('@/views/Dashboard.vue')
// const Table = () => import('@/views/Table.vue')
// const Form = () => import('@/views/Form.vue')
// const ComplexForm = () => import('@/views/ComplexForm.vue')

// 常量路由表
export const constantRouterMap = [
  {
    path: '/login',
    component: Login,
    name: 'login',
    hidden: true
  },
  {
    path: '/',
    name: '首页',
    component: Layout,
    redirect: '/dashboard',
    hidden: true,
    children: [
      {
        path: '/dashboard',
        name: '面板',
        component: Dashboard
      }
    ]
  },
  {
    path: '/404',
    name: '404',
    component: NotFound
  }
]

// 404、403等页面必须放在最后
export const suffixRouterMap = [
  {
    path: '*',
    redirect: '/404',
    hidden: true
  }
]

const router = new Router({
  routes: constantRouterMap
})

const whiteList = ['/login']
router.beforeEach((to, from, next) => {
  NProgress.start()
  // 从vuex中读取token
  if (store.getters.token) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      const roles = store.getters.roles
      if (roles && roles.length === 0) {
        // 第一次进入非登录路由需要获取用户信息
        store.dispatch('GetInfo').then(res => {
          next({ ...to })
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  if (to.path === '/login') {
    // 去login之前清空store中的menu
    store.commit('SET_MENU', [])
  }
  NProgress.done() // 结束Progress
})

export default router
